/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package searching;

/**
 *
 * @author Akram
 */
public final class BinarySearch<T extends Comparable> {

    private T[] array;
    private Class<T> classType;

    public BinarySearch(T[] array, Class<T> classType) {
        if (array == null) {
            throw new NullPointerException();
        }
        if (array.length > 0) {
            if (!classType.isInstance(array[0])) {
                throw new ClassCastException();
            }
        }
        this.array = array;
        this.classType = classType;
    }

    public final int search(T key) {
        int high = array.length - 1;
        int low = 0;
        while (low <= high) {
            int mid = (int) Math.floor((low + high) / 2);
            if (array[mid].compareTo(key) == 0) {
                return mid;
            } else if (array[mid].compareTo(key) < 0) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return -1;
    }
}
